import Vue from 'vue'
import axios from 'axios'
import { getBaseURL } from '@/config/server'
const _this = Vue.prototype

export default {
  state: {
    approveTodoCount: 0, // 待办数量
    orderCount: { // 工单数量
      dfp: 0, // 待分派
      dpd: 0, // 待派单
      dcl: 0, // 待处理
      dsh: 0 // 待审核
    }
  },
  actions: {
    // 获取审批待办数量
    async getApproveTodoCount({ commit }) {
      try {
        // 使用UniApp跨平台存储API
        const appOrgInfo = uni.getStorageSync('appOrgInfo')
        if (!appOrgInfo) return

        const { memberId, orgId } = JSON.parse(appOrgInfo)
        if (!memberId || !orgId) {
          console.error('缺少用户或组织ID')
          return
        }

        // 获取token
        let res = await _this.$Geting(_this.$api.getTokenByAppServiceId, {
          appServiceId: 'flow_approve',
          orgId,
          memberId
        })

        // 请求待办数量
        const result = await axios({
          method: 'post',
          url: `${getBaseURL()}${_this.$api.getShenpiCount}`,
          data: {
            pageBean: { page: 1, showTotal: true },
            querys: []
          },
          headers: {
            'X-Access-Source': 'roc',
            'X-Access-Token': res.data.accessToken || ''
          }
        })

        // 处理返回结果
        const num = result.data.total
        const count = isNaN(num) ? 0 : num
        commit('setApproveTodoCount', count)
      } catch (error) {
        console.error('获取审批待办数量失败:', error)
      }
    },

    // 获取工单待办数量
    async getOrderCount({ commit }) {
      try {
        // 使用UniApp跨平台存储API
        const appOrgInfo = uni.getStorageSync('appOrgInfo')
        if (!appOrgInfo) return

        const { memberId, orgId } = JSON.parse(appOrgInfo)
        if (!memberId || !orgId) {
          console.error('缺少用户或组织ID')
          return
        }

        // 获取token
        let res = await _this.$Geting(_this.$api.getTokenByAppServiceId, {
          appServiceId: 'order_todo_app',
          orgId,
          memberId
        })
        const token = res.data.accessToken

        // 请求工单数量
        const result = await axios({
          method: 'post',
          url: `${getBaseURL()}${_this.$api.getTodoOrderList}`,
          data: {
            pageNum: 1,
            pageSize: 10,
            query: {
              deptId: '', // 当前项目节点Id
              candidates: memberId || '', // 当前登陆人memberId 必填
            }
          },
          headers: {
            'X-Access-Source': 'roc',
            'X-Access-Token': token || ''
          }
        })

        // 处理返回结果
        const data = result.data.data?.nodeCodeWebDto
        commit('setOrderCount', data)
      } catch (error) {
        console.error('获取工单待办数量失败:', error)
        // 错误时重置工单数量
        commit('setOrderCount', null)
      }
    }
  },
  mutations: {
    // 设置审批的待办数量
    setApproveTodoCount(state, payload) {
      state.approveTodoCount = payload
    },
    // 设置工单数量
    setOrderCount(state, payload) {
      if (payload) {
        state.orderCount = {
          dfp: payload.receivingNum || 0, // 待分派 也即待接单
          dpd: payload.dispatchNum || 0, // 待派单
          dcl: payload.handleNum || 0, // 待处理
          dsh: payload.examineNum || 0 // 待审核
        }
      } else {
        console.log('未获取到工单数量数据')
        state.orderCount = {
          dfp: 0,
          dpd: 0,
          dcl: 0,
          dsh: 0
        }
      }
    }
  }
}